﻿using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid;
using Fluid.Ast;
using ZYing.LiquidThemeEngine.Objects;
using ZYing.LiquidThemeEngine.Paginating;

namespace ZYing.LiquidThemeEngine.Tags
{
    public static class PaginatingTags
    {
        public static async ValueTask<Completion> PaginateAsync((Expression Expression, long PageSize) args, IReadOnlyList<Statement> statements, TextWriter writer, TextEncoder encoder, TemplateContext context)
        {
            var value = await args.Expression.EvaluateAsync(context);
            if (value == null || value is not PaginationValue paginationValue) return Completion.Normal;
            context.EnterChildScope();
            await paginationValue.PaginateAsync((int)args.PageSize);
            var paginate = new Paginate(paginationValue);
            context.SetValue(Constants.ObjectNames.Paginate, paginate);
            await statements.RenderStatementsAsync(writer, encoder, context);
            context.ReleaseScope();
            return Completion.Normal;
        }
    }
}